<template>
  <view>
    <form @submit="formSubmit" @reset="formReset">
      <view class="uni-form-item uni-column">
        <view class="title">姓名</view>
        <input class="uni-input" name="nickname" placeholder="请输入姓名" />
      </view>
      <view class="uni-form-item uni-column">
        <view class="title">性别</view>
        <radio-group name="gender">
          <radio value="男">男</radio>
          <radio value="女">女</radio>
        </radio-group>
      </view>
      <view class="uni-form-item uni-column">
        <view class="title">爱好</view>
        <checkbox-group name="loves">
          <checkbox value="运动">运动</checkbox>
          <checkbox value="阅读">阅读</checkbox>
          <checkbox value="音乐">音乐</checkbox>
        </checkbox-group>
      </view>
      <view class="uni-form-item uni-column">
        <view class="title">年龄</view>
        <slider value="20" name="age" show-value></slider>
      </view>
      <view class="uni-form-item uni-column">
        <view class="title">保留选项</view>
      </view>
      <view class="uni-btn-v">
        <button form-type="submit">Submit</button>
        <button type="default" form-type="reset">Reset</button>
      </view>
    </form>
  </view>
</template>

<script setup>

const graceChecker = {
  check: (formData, rule) => {
    
    for (const item of rule) {
      if (item.checktype === "notnull" && !formData[item.name]) {
        return false;
      }
    }
    return true;
  },
  error: "校验错误信息",
};

const formSubmit = (e) => {
  console.log("form发生了submit事件，携带数据为：" + JSON.stringify(e.detail.value));
  const rule = [
    {
      name: "nickname",
      checktype: "string",
      checkRule: "1,3",
      errorMsg: "姓名应为1-3",
    },
    {
      name: "gender",
      checktype: "in",
      checkRule: "男，女",
      errorMsg: "请选择性别",
    },
    {
      name: "loves",
      checktype: "notnull",
      checkRule: "",
      errorMsg: "请选择爱好",
    },
  ];
  const formData = e.detail.value;
  const checkRes = graceChecker.check(formData, rule);
  if (checkRes) {
    uni.showToast({ title: "验证通过！", icon: "none" });
  } else {
    uni.showToast({ title: graceChecker.error, icon: "none" });
  }
  uni.showModal({
    content: "表单数据内容：" + JSON.stringify(e.detail.value),
    showCancel: false,
  });
};

const formReset = (e) => {
  console.log("清空数据");
};
</script>

<style>

</style>